/**
 *
 */
package com.feizhi.common.controller;

import java.util.List;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StringUtils;

import com.feizhi.common.convert.Converter;
import com.feizhi.common.service.ListQueryService;

/**
 * @author shuaqiu 2013年11月24日
 *
 */
public class ControllerUtil {

	/**
	 * @param range
	 * @return
	 */
	private static long[] range(final String range) {
		if (StringUtils.hasText(range) && range.length() > 1) {
			// users=0-24
			String[] arr = range.split("=");
			if (arr.length != 2) {
				return null;
			}

			arr = arr[1].split("-");
			if (arr.length != 2) {
				return null;
			}
			final Long b = Converter.toLong(arr[0]);
			final Long e = Converter.toLong(arr[1]);
			return new long[] { b + 1, e + 1 };
		}

		return null;
	}

	public static <T> HttpEntity<List<T>> doQuery(final ListQueryService<T> service,
			final String sort, final Map<String, Object> params, final String range) {
		final long[] rangeArr = range(range);

		final HttpHeaders header = new HttpHeaders();

		if (rangeArr != null) {
			final long count = service.matchedRecordCount(params);
			header.set("Content-Range", " items " + (rangeArr[0] - 1) + "-"
					+ (rangeArr[1] - 1) + "/" + count);
		}

		final List<T> list = service.query(sort, params, rangeArr);
		final HttpEntity<List<T>> entity = new HttpEntity<List<T>>(list, header);

		return entity;
	}

}
